package com.dbapp.garden.controller.teaching;

import com.dbapp.garden.common.DataTableUtils;
import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.GardenCourseSeries;
import com.dbapp.garden.entity.GardenSwipeCardRule;
import com.dbapp.garden.service.GardenCourseSeriesService;
import com.dbapp.garden.service.GardenSwipeCardRuleService;
import com.dbapp.garden.vm.CardRuleVm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author by gangzi on 2017/11/12.
 * 按此刷卡 控制器类
 */

@Controller
public class GardenSwipeCardRulesController {

    @Autowired
    private GardenSwipeCardRuleService ruleService;
    @Autowired
    private GardenCourseSeriesService seriesService;

    @GetMapping("/swipe_card_add")
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE_ADD')")
    public String toSwipeCardAddPage(HttpServletRequest request, Model model){
        Map<String,Object> map=new HashMap<>(16);
        List<GardenCourseSeries> series=seriesService.getCouseSeriesList(map);

        model.addAttribute("series",series);
        return "teaching/swipe_card_add";
    }
    @GetMapping("/swipe_card/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE_EDIT')")
    public String toSwipeCardAddPage(HttpServletRequest request,@PathVariable("id") Integer id, Model model){
        Map<String,Object> map=new HashMap<>(16);
        List<GardenCourseSeries> series=seriesService.getCouseSeriesList(map);
        GardenSwipeCardRule cardRule=ruleService.findById(id);

        model.addAttribute("series",series);
        model.addAttribute("cardRule",cardRule);
        String time=cardRule.getSwipeTime();
        String time1="";
        String time2="";
        if (time.contains("至")){
            time1=time.substring(0,time.lastIndexOf("至"));
            time2=time.substring(time.lastIndexOf("至"));
        }
        model.addAttribute("time1",time1);
        model.addAttribute("time2",time2);
        return "teaching/swipe_card_edit";
    }

    @PostMapping("/cardrulelist")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE')")
    public Map<String, ?> cardRuleList(HttpServletRequest request, String param) {

        Map<String, Object> paramMap = DataTableUtils.parseParam(param);
        if (paramMap == null) {
            return RenderJSON.makeMap(-1, "参数不合法！", null, "");
        }
        String sEcho = (String) paramMap.get("sEcho");
        String sSearch = (String) paramMap.get("sSearch");
        int iDisplayStart = (int) paramMap.get("iDisplayStart");
        int iDisplayLength = (int) paramMap.get("iDisplayLength");

        paramMap.clear();
        paramMap.put("search", sSearch);
        paramMap.put("start", iDisplayStart);
        paramMap.put("limit", iDisplayLength);

        List<GardenSwipeCardRule> cardRuleList = ruleService.getCardRuleList(paramMap);
        Integer count = ruleService.getCardRuleCount(paramMap);

        return RenderJSON.makePagenateMap(1, "获取成功", sEcho, count, count, cardRuleList, "");
    }

    @PostMapping("/cardrule")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE_ADD')")
    public Map<String, ?> addCardRule(HttpServletRequest request,
                                       @RequestBody @Valid CardRuleVm cardRuleVm) {
        GardenSwipeCardRule cardRule = new GardenSwipeCardRule();
        cardRule.setCourseHourType(cardRuleVm.getCourseHourType());
        cardRule.setDeductHour(cardRuleVm.getDeductHour());
        cardRule.setFeeType(cardRuleVm.getFeeType());
        cardRule.setRulesState(cardRuleVm.getRulesState());
        cardRule.setRulesName(cardRuleVm.getRulesName());
        cardRule.setSwipeCardCount(cardRuleVm.getSwipeCardCount());
        String time=cardRuleVm.getSwipeTime();
        if (StringUtils.isNotEmpty(time)){
            time=time.replace(",","至");
        }
        cardRule.setSwipeTime(time);
        cardRule.setCreateTime(new Date());
        cardRule.setUpdateTime(new Date());

        Integer result = ruleService.save(cardRule);

        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，添加成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，添加失败！", "error");
        }

    }
    @DeleteMapping("/cardrule/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE_DELETE')")
    public Map<String, ?> deleteCardRule(HttpServletRequest request,
                                          @PathVariable("id") Integer id) {

        Integer result = ruleService.delete(id);
        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，删除成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，删除失败！", "error");
        }

    }
    @PutMapping("/cardrule/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE_EDIT')")
    public Map<String, ?> editCardRule(HttpServletRequest request,
                                        @PathVariable("id") Integer id,@RequestBody @Valid CardRuleVm cardRuleVm) {

        GardenSwipeCardRule cardRule = ruleService.findById(id);
        if (cardRule==null){
            return RenderJSON.makeStandMap(1, "对不起，该刷卡规则不存在，编辑失败！", "error");
        }
        cardRule.setCourseHourType(cardRuleVm.getCourseHourType());
        cardRule.setDeductHour(cardRuleVm.getDeductHour());
        cardRule.setFeeType(cardRuleVm.getFeeType());
        cardRule.setRulesState(cardRuleVm.getRulesState());
        cardRule.setRulesName(cardRuleVm.getRulesName());
        cardRule.setSwipeCardCount(cardRuleVm.getSwipeCardCount());
        String time=cardRuleVm.getSwipeTime();
        if (StringUtils.isNotEmpty(time)){
            time=time.replace(",","至");
        }
        cardRule.setSwipeTime(time);
        cardRule.setId(id);
        cardRule.setUpdateTime(new Date());

        Integer result = ruleService.save(cardRule);

        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }

    }

    @PutMapping("/cardrulestate/{id}")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_CARD_RULE_EDIT')")
    public Map<String, ?> editCardRuleState(HttpServletRequest request,
                                        @PathVariable("id") Integer id,Integer state) {

        GardenSwipeCardRule cardRule = ruleService.findById(id);
        if (cardRule==null){
            return RenderJSON.makeStandMap(1, "对不起，该刷卡规则不存在，编辑失败！", "error");
        }
        cardRule.setRulesState(state);
        cardRule.setUpdateTime(new Date());

        Integer result = ruleService.save(cardRule);

        if (result != null && result > 0) {
            return RenderJSON.makeStandMap(1, "恭喜您，状态更新成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，状态更新失败！", "error");
        }

    }

}
